package com.ebt.m.customer.ui;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.ebt.m.R;
import com.ebt.m.customer.adapter.CommonPagerAdapter;
import com.ebt.m.customer.entity.Attachment;
import com.ebt.m.customer.event.OnAttachDeleteEvent;
import com.ebt.m.customer.util.PolicyAttachOpt;
import com.ebt.m.customer.view.ConfirmDialog;
import com.ebt.m.view.PointerIndexViewPager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import uk.co.senab.photoview.PhotoView;

/**
 * 图片预览
 * Created by archer.qi on 2016/12/9.
 */
public class ImagePreviewActivity extends Activity implements View.OnClickListener {

    public static final String EXTRA_DATA = "data";
    public static final String EXTRA_POSITION = "position";
    public static final String EXTRA_FLAG = "from";


    private ImageView mIvBack;
    private TextView mTvPicturePosition;
    private ImageView mIvDel;

    private PointerIndexViewPager mViewPager;
    private List<View> mViews = new ArrayList<>();
    private CommonPagerAdapter mAdapter;

    private ConfirmDialog confirmDialog;

    private List<Attachment> attachmentList;
    private int currPosition;
    private int flag;

    // mViews对应的数据保存列
    private List<Attachment> mViewData = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_preview);
        setupViews();
        init();
    }

    private void setupViews() {
        mIvBack = (ImageView) findViewById(R.id.preview_top_back);
        mTvPicturePosition = (TextView) findViewById(R.id.preview_top_no);
        mIvDel = (ImageView) findViewById(R.id.preview_top_del);

        mViewPager = (PointerIndexViewPager) findViewById(R.id.preview_viewpager);

        mIvBack.setOnClickListener(this);
        mIvDel.setOnClickListener(this);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                currPosition = position;
                setPosition();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void init() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            attachmentList = (List<Attachment>) bundle.getSerializable(EXTRA_DATA);
            currPosition = bundle.getInt(EXTRA_POSITION);
            flag = bundle.getInt(EXTRA_FLAG);
        }

        if (flag == 0) {
            mIvDel.setVisibility(View.GONE);
        }

        setPosition();
        initViews();
        setPagerAdapter();
        mViewPager.setCurrentItem(currPosition, true);
    }

    private void initViews() {
        if (attachmentList != null) {
            int len = attachmentList.size();
            for (int i = 0; i < len; i++) {
                if (attachmentList.get(i).option == -1) {
                    continue;
                }
                mViews.add(getView(attachmentList.get(i).getUrl(), attachmentList.get(i).getPath()));
                mViewData.add(attachmentList.get(i));
            }
        }
    }

    private View getView(String url, String path) {
        View view = getLayoutInflater().inflate(R.layout.view_photo, null);
        PhotoView photoView = (PhotoView) view.findViewById(R.id.photoView);

        if (TextUtils.isEmpty(path)) {
            if (!TextUtils.isEmpty(url)) {
                display(url, photoView);
            }
        } else {
            display(path, photoView);
        }

        return view;
    }

    /**
     * 设置当前页数/总数
     */
    private void setPosition() {
        int total = getTotal();
        if (currPosition >= 0 && currPosition < total) {
            mTvPicturePosition.setText((currPosition + 1) + "/" + total);
        }
    }

    /**
     * 统计当前页面总数
     *
     * @return
     */
    public int getTotal() {
        if (attachmentList == null) {
            return 0;
        }
        int total = 0;
        for (Attachment a : attachmentList) {
            if (a != null && a.option > -1) {
                total++;
            }
        }
        return total;
    }

    private void display(String url, PhotoView view) {
        Glide.with(this).load(url).into(view);
    }

    private void setPagerAdapter() {
        mAdapter = new CommonPagerAdapter(mViews);
        mViewPager.setAdapter(mAdapter);
    }

    private void showDeleteDialog() {
        if (confirmDialog == null) {
            confirmDialog = new ConfirmDialog(ImagePreviewActivity.this);
        }
        confirmDialog.setMessage("确定删除该附件吗？")
                .setPositiveButton("删除", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        confirmDialog.dismiss();
                        List<Attachment> newAttachments = PolicyAttachOpt.deleteAttach(attachmentList, mViewData.get(currPosition));

                        if (PolicyAttachOpt.hasDeleted) {
                            mViews.remove(currPosition);
                            mViewData.remove(currPosition);
                            currPosition = 0;
                            setPosition();
                            setPagerAdapter();
                            mViewPager.setCurrentItem(0);

                            EventBus.getDefault().post(new OnAttachDeleteEvent(newAttachments));

                            if (mViews.size() == 0) {
                                finish();
                            }
                        }
                    }
                }).show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.preview_top_back:
                finish();
                break;
            case R.id.preview_top_del:
                // 删除
                showDeleteDialog();
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (confirmDialog != null) {
            confirmDialog.dismiss();
        }
    }
}
